/*
 * Tencent is pleased to support the open source community by making Tencent Shadow available.
 * Copyright (C) 2019 THL A29 Limited, a Tencent company.  All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License"); you may not use
 * this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 *     https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.yc.shadowdemo

import android.annotation.SuppressLint
import android.content.Context
import com.yc.shadowdemo.YcFileUtils
import com.yc.shadowdemo.YcPluginHostConstant
import java.io.File
import java.util.concurrent.Executors

class PluginHelper private constructor() {
    var pluginManagerFile: File? = null
    var pluginZipFile: File? = null
    var singlePool = Executors.newSingleThreadExecutor()
    private var mContext: Context? = null
    fun init(context: Context) {
        pluginManagerFile = File(context.filesDir, sPluginManagerName)
        pluginZipFile = File(context.filesDir, sPluginZip)
        mContext = context.applicationContext
        singlePool.execute { preparePlugin() }
    }

    private fun preparePlugin() {
        try {
            YcFileUtils.copyFile(mContext, sPluginManagerName, YcPluginHostConstant.MANAGER_APK_PATH)
            YcFileUtils.copyFile(mContext, sPluginZip, YcPluginHostConstant.ChildZipPath.MODULE_1)
            //            InputStream is = mContext.getAssets().open(sPluginManagerName);
//            FileUtils.copyInputStreamToFile(is, pluginManagerFile);

//            InputStream zip = mContext.getAssets().open(sPluginZip);
//            FileUtils.copyInputStreamToFile(zip, pluginZipFile);
        } catch (e: Exception) {
            throw RuntimeException("从assets中复制apk出错", e)
        }
    }

    companion object {
        /**
         * 动态加载的插件管理apk
         */
        const val sPluginManagerName = "shadowmanager-debug.apk"

        /**
         * 动态加载的插件包，里面包含以下几个部分，插件apk，插件框架apk（loader apk和runtime apk）, apk信息配置关系json文件
         */
        //    public final static String sPluginZip = BuildConfig.DEBUG ? "plugin-debug.zip" : "plugin-release.zip";
        const val sPluginZip = "plugin-debug.zip"
        val instance = PluginHelper()
    }
}